import qb
import time
import datetime
import qb_database_
import os
import re
q = qb_database_.QubeDatabase()
QUBE_TIME = 946702800
time_now_globle = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

def counter(last=[0]):
    next = last[0] + 1
    last[0] = next
    return next

def maktxt():
    time_now = time.strftime('%Y%m%d',time.localtime(time.time()))
    b = os.path.exists('/show/WDN/misc/dept/lgt/RenderFarm/archive/retry_list')
    if b:
        pass
    else:
        print 'make dir is ok'
        os.makedirs('/show/WDN/misc/dept/lgt/RenderFarm/archive/retry_list')
    file_path = '/show/WDN/misc/dept/lgt/RenderFarm/archive/retry_list/' + time_now + '.txt'
    os.system('touch '+file_path)
    return file_path


def auto_retry_filed():
    job = q.auto_job(query='where status = 336 and ((SELECT * FROM jobidmax)-60000) < id')
    for item in job:
        jobid = int(item[0])
        job_pid = q.job_agenda(jobid, 'id, name, status, timestart, timecomplete, host')
        for item_p in job_pid:
            time_star = datetime.datetime.fromtimestamp(item_p[3] + QUBE_TIME)
            now = datetime.datetime.now()
            time_use = (now - time_star).total_seconds()
            file_path = maktxt()
            if (time_use>=0) and (item_p[2] == 32):
                f2 = open(file_path, 'r').read()
                word_occurs = len(re.findall('%s:%s' % (item[0], item_p[1]), f2))
                if word_occurs > 2:
                    pass
                else:
                    f1 = open(file_path, 'a+')
                    f1.writelines('%s : %s:%s\n'%(time_now_globle,item[0],item_p[1]))
                    f1.close()
                if word_occurs < 2:
                    print '-----%s------'%time_now_globle
                    print '-----retry------id=%s.%s'%(item[0],item_p[0]),qb.retrywork('%s:%s'%(item[0],item_p[1]))
                    print 'the job: %s:%s is retry %s times' % (item[0], item_p[1], word_occurs)
                else:
                    pass


if __name__ == '__main__':
   while True:
       try:
        auto_retry_filed()
       except:
           print "timestamp wrong"
           auto_retry_filed()

